/*
 *  Copyright (C) 2011 Dan de la Cruz <ddcruzg@gmail.com>
 * 
 *  Viajero Fashion is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  Viajero Fashion is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.vfashion.controller;

import com.vfashion.domain.Cliente;
import com.vfashion.model.VfashionModel;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Dan de la Cruz <ddcruzg@gmail.com>
 */

public class VFsession extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String alias = req.getServletPath();
        System.out.println("Servlet : " + alias);
        if (alias.equals("/Login")) {
            login(req, resp);

        } else if (alias.equals("/Logout")) {
            logout(req, resp);
        }

    }

    private void login(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        HttpSession session = req.getSession(true);
        String usuario = (String) req.getParameter("usuario");
        String clave = (String) req.getParameter("clave");
        System.out.println("usuario : " + usuario);
        System.out.println("clave : " + clave);
        String pagina_jsp = "login.jsp";
        try {
            VfashionModel mdlVfashion = new VfashionModel();
            Cliente cliente = mdlVfashion.login(usuario, clave);
            session.setAttribute("CLIENTE", cliente);
            session.setAttribute("login", "ok");
            pagina_jsp = "ShowPkgs";
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage()); 
            pagina_jsp = "login.jsp";
        } finally{
            RequestDispatcher rd = req.getRequestDispatcher(pagina_jsp);
            rd.forward(req, resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        HttpSession session = req.getSession(true);
        session.invalidate();
        RequestDispatcher rd = req.getRequestDispatcher("logout.jsp");
        rd.forward(req, resp);
    }
}
